package com.qdlc.p2p.biz.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import com.qdlc.p2p.biz.service.LinkService;
import com.qdlc.p2p.dal.dto.Link;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.qdlc.p2p.biz.service.ArticleService;
import com.qdlc.p2p.biz.service.SystemConfigService;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.BorrowConfigDao;
import com.qdlc.p2p.dal.dao.SystemConfigDao;
import com.qdlc.p2p.dal.dto.BorrowConfig;
import com.qdlc.p2p.dal.dto.Site;
import com.qdlc.p2p.dal.dto.SystemConfig;
import com.qdlc.p2p.dal.model.SystemConfigModel;
import com.qdlc.p2p.dal.model.Tree;

@Service("systemConfigService")
public class SystemConfigServiceImpl implements SystemConfigService {

    private Logger logger = Logger.getLogger(SystemConfigServiceImpl.class);

    @Resource
    private SystemConfigDao systemConfigDao;

    @Resource
    private BorrowConfigDao borrowConfigDao;

    @Resource
    private ArticleService articleService;

    @Resource
    private LinkService linkService;

    @Override
    public PageDataList<SystemConfigModel> list(SystemConfigModel model) {
        return systemConfigDao.list(model);
    }

    @Override
    public SystemConfig find(long id) {
        return systemConfigDao.find(id);
    }

    @Override
    public void add(SystemConfig systemConfig) {
        systemConfigDao.save(systemConfig);
    }

    @Override
    public void update(SystemConfig systemConfig) {
        systemConfigDao.update(systemConfig);
    }

    @Override
    public void clean() {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        ServletContext context = wac.getServletContext();

        Tree<Site> tree = articleService.getSiteTree();
        context.setAttribute("tree", tree);

        List<BorrowConfig> borrowConfigList = borrowConfigDao.findAll();
        Map<Object, Object> map = new HashMap<Object, Object>();
        for (BorrowConfig config : borrowConfigList) {
            map.put(config.getId(), config);
        }
        Global.BORROW_CONFIG_MAP = map;
        Global.BORROW_CONFIG_LIST = borrowConfigList;

        setWebConfig();
    }

    @Override
    public void setWebConfig() {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        ServletContext context = wac.getServletContext();
        Set<String> nidSet = SystemConfigHelper.getNidSet();
        for (String nid : nidSet) {
            String value = SystemConfigHelper.getValueFromDB(nid);
            logger.debug("config: " + nid + "------" + value);
            context.setAttribute(nid, value);

            if (nid.equals("theme_dir") && StringUtil.isBlank(value)) {
                context.setAttribute("theme_dir", "/themes/soonmes_default");
            }
        }
        context.setAttribute("webroot", context.getContextPath());
    }

    @Override
    public void checkNid(String nid) {
        QueryParam param = QueryParam.getInstance();
        param.addParam("nid", nid.trim());
        List<SystemConfig> list = systemConfigDao.findByCriteria(param);
        if (list.size() != 0) {
            throw new BusinessException("该标识已存在", BusinessException.TYPE_JSON);
        }
    }

    @Override
    public SystemConfig findByNid(String nid) {
        QueryParam param = QueryParam.getInstance();
        param.addParam("nid", nid.trim());
        List<SystemConfig> list = systemConfigDao.findByCriteria(param);
        if (list.isEmpty()) {
            logger.debug("系统规则未配置或配置错误 nid=" + nid);
            throw new BusinessException("系统规则未配置或配置错误", BusinessException.TYPE_JSON);
        } else {
            return list.get(0);
        }
    }

    @Override
    public void cleanLink() {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        ServletContext context = wac.getServletContext();
        List<Link> list = linkService.findByType(1);
        context.setAttribute("link", list);
    }
}
